package org.dylan.keepnote;

import java.io.File;
import java.io.FileFilter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * 
 * @Copyright: Copyright (c) 2013 FFCS All Rights Reserved
 * @Company: 北京福富软件有限公司
 * @author 陈作朋 Oct 26, 2013
 * @version 1.00.00
 * @history:
 * 
 */
public class KNoteExtractor {

	private final static Logger logger = LoggerFactory.getLogger(KNoteExtractor.class);

//	public static int seq = 607; //JAVA
	
	public static int seq = 1;  //Linux

	private static File getNoteFile(File dir) {
		return new File(dir, "node.xml");
	}

	private static KNote parseNoteAttr(File file) throws Exception {
		String content = FileUtils.readFileToString(file);

		KNote note = new KNote();
		note.setPath(file.getParentFile());

		Matcher matcher = Pattern.compile("<key>(.*?)</key><.*?>(.*?)</.*?>").matcher(content);

		while (matcher.find()) {
			String key=matcher.group(1);
			String value=matcher.group(2);
			if (note.getAttr(key) == null) {
				note.addAttr(key, value);
			}
		}
		note.setContentType(note.getAttr("content_type"));
		note.setTitle(note.getAttr("title").replaceAll(",", "_").trim());
		return note;
	}

	private static void extractNoteContent(KNote note) throws Exception {
		File content;
		if (note.isText()) {
			content = new File(note.getPath(), "page.html");
		} else if (note.isPDF() || note.isEXE() || note.isShell() || note.isTar() || note.isChm() || note.isXml() || note.isZip() || note.isDOC() || note.isPPT() || note.isRAR() || note.isJAVA() || note.isTXT() || note.isJAR()|| note.isXDIFF()) {
			content = new File(note.getPath(), note.getAttr("payload_filename"));
		} else if (note.isNoteDir()) {
			return;
		} else {
			logger.info("不支持的Note:{}", note);
			return;
		}
		if (!content.exists()) {
			throw new Exception("content is not exists");
		}
		note.setContent(content);
	}

	private static void extractImgs(KNote note) throws Exception {
		File[] imgs = note.getPath().listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				String ext = FilenameUtils.getExtension(pathname.getAbsolutePath());
				return "gif".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext);
			}
		});
		for (File img : imgs) {
			note.addImg(img);
		}
	}

	public static KNote extract(KNote pnote, File path) throws Exception {

		if ("__NOTEBOOK__".equals(path.getName()) || "__TRASH__".equals(path.getName())) {

		}

		File noteFile = getNoteFile(path);
		KNote note = parseNoteAttr(noteFile);
		extractNoteContent(note);
		extractImgs(note);
		note.setSeq(seq++);
		if (pnote != null) {
			note.setParent(pnote);
			pnote.addChild(note);
		}
		File[] dirs = path.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.isDirectory() && !("__NOTEBOOK__".equals(pathname.getName()) || "__TRASH__".equals(pathname.getName()));
			}
		});

		for (File dir : dirs) {
			extract(note, dir);
		}
		return note;
	}

	public static KNote extract(String path) throws Exception {
		return extract(null, new File(path));
	}

	public static void main(String[] args) throws Exception {
		String path = "/home/dylan/Data/n/Java";
		KNote note = extract(path);
//		System.out.println(note);
		System.out.println("sid:"+KNoteExtractor.seq);
	}

}
